import {
  isAffairValid,
  BatchParam,
  SecretCheck,
  lockWorkflow,
  unlockWorkflow,
  doPigeonholeCheck,
  releaseWorkflowByAction,
  onBeforeWorkflowOperationValidate,
  executeWorkflowBeforeEvent,
  releaseApplicationButtons,
  generateRandomNumber,
  beforeSubmit,
  _designWorkflow,
  setRelationAuth
} from '../collaborationFunc/collaboration';

import collaboration from '@/utils/collaboration';

import {toastForward} from "../../../utils";
import * as Fiber from 'fiber';

let loadingInstance = {
  init() { },
  close() { },
  show() { },
  empty:true,
};
export default {
  data() {
    return {};
  },
  computed: {
    isPigeonholeBtn() {
      const { resources } = this;
      if (!resources) return false;
      const list = [
        'F04_docIndex',
        'F04_myDocLibIndex',
        'F04_accDocLibIndex',
        'F04_proDocLibIndex',
        'F04_eDocLibIndex',
        'F04_docLibsConfig'
      ];
      return list.some((item) => resources.includes(item));
    },
    isNewCellBtn() {
      const { resources } = this;
      if (!resources) return false;
      return resources.contains('F01_newColl');
    },
    isEmailBtn() {
      const { resources } = this;
      if (!resources) return false;
      return resources.contains('F12_mailcreate');
    }
  },
  methods: {
    initToolbar() {
      const { newColNodePolicy, canDel, isFormAdvanced, isV5Member, hasDumpData, addinMenus } = this;
      const result = [];
      const newColNodePolicyProps = ['forward', 'pigeonhole', 'cancel', 'editWorkFlow', 'repeatSend'];
      newColNodePolicyProps.forEach((prop) => {
        if (newColNodePolicy[prop]) {
          const temProp = prop[0].toUpperCase() + prop.substring(1);
          const item = this[`set${temProp}Item`]();
          if (item) {
            item.disabled = false;
            result.push(item);
          }
        }
      });
      if (canDel) {
        result.push({
          id: 'delete',
          name: $.i18n('common.toolbar.delete.label'),
          disabled: false
        });
      }

      if (isFormAdvanced && isV5Member) {
        result.push({
          id: 'relationAuthority',
          name: $.i18n('common.toolbar.relationAuthority.label'),
          disabled: false
        });
      }

      if (hasDumpData) {
        result.push({
          id: 'currentData',
          name: $.i18n('collaboration.portal.listDone.currentData.js'),
          disabled: false
        });
        result.push({
          id: 'dumpData',
          name: $.i18n('collaboration.portal.listDone.dumpData.js'),
          disabled: false
        });
      }
      if (addinMenus.length) {
        addinMenus.forEach((menu) => {
          result.push({
            id: menu.id,
            name: menu.name,
            disabled: false
          });
        });
      }
      // 扫一扫
      if (this.isHaveSmartCodePermission()) {
        result.push(this.smartCodeBtnInfo);
      }

      this.allToolBtns = result;
    },
    setForwardItem() {
      const { isNewCellBtn, isEmailBtn, emailShow } = this;
      //判断是否有新建协同的资源权限，如果没有则屏蔽转发协同
      let submenu = [];
      if (isNewCellBtn) {
        //协同
        submenu.push({
          name: $.i18n('common.toolbar.transmit.col.label'),
          id: 'newColl'
        });
      }
      //判断是否有转发邮件的资源权限，如果没有则屏蔽转发协同
      if (isEmailBtn && emailShow) {
        //邮件
        submenu.push({
          name: $.i18n('common.toolbar.transmit.mail.label'),
          id: 'email'
        });
      }
      return {
        id: 'transmit',
        name: $.i18n('common.toolbar.transmit.label'),
        subMenu: submenu
      };
    },
    setPigeonholeItem() {
      const { isPigeonholeBtn, hasDoc } = this;
      if (isPigeonholeBtn && hasDoc) {
        return {
          id: 'pigeonhole',
          name: $.i18n('common.toolbar.pigeonhole.label')
        };
      }
    },
    setCancelItem() {
      return {
        id: 'cancelWorkFlow',
        name: $.i18n('common.toolbar.repeal.label')
      };
    },
    setEditWorkFlowItem() {
      return {
        id: 'editWorkFlow',
        name: $.i18n('common.design.workflow.label')
      };
    },
    setRepeatSendItem() {
      return {
        id: 'resend',
        name: $.i18n('common.toolbar.resend.label')
      };
    },
    setHandoverItem() {
      // const { showHandoverButton, isV5Member } = this;
      // if (showHandoverButton && isV5Member) {
      //   let submenu = [];
      //   submenu.push({
      //     name: $.i18n('handover.button.to.js'),
      //     id: 'to'
      //   });
      //   submenu.push({
      //     name: $.i18n('handover.button.from.js'),
      //     id: 'from'
      //   });
      //   return {
      //     id: 'handover',
      //     name: $.i18n('handover.grid.matters.js'),
      //     subMenu: submenu
      //   };
      // }
    },
    // 协同
    newCollClickHandle() {
      const { selectedRows, isSecretLevelEnable, listFrom } = this;
      const validateResult = this.newCollClickValidate();
      if (!validateResult) return;
      const sendData = [];
      for (let i = 0; i < selectedRows.length; i++) {
        const row = selectedRows[i];
        let {
          applicationCategoryKey,
          app,
          summaryId,
          subject,
          objectId,
          affairId,
          id,
          templeteId,
          superNode
        } = row;
        const application = applicationCategoryKey || app;
        const applicationValidateResult = this.rowApplicationValidate(application);
        if (!applicationValidateResult) return;
        summaryId = summaryId || objectId;
        affairId = affairId || id;
        if (listFrom === 'listWaitSend') {
          if (templeteId) {
            const result = window.callBackendMethod(
              'colManager',
              'isTemplateDeleted',
              templeteId
            );
            if (String(result) === '1') {
              //被删除
              Fiber.message.warning($.i18n('template.coll.not.ues.js', subject));
              return;
            }
          }
          if (superNode) {
            Fiber.message.warning($.i18n('workflow.supernode.msg.not_transmit.js'));
            return;
          }
        }
        sendData.push({
          summaryId,
          affairId
        });
      }
      this.transmitColById(sendData);
    },
    newCollClickValidate() {
      const { selectedRows, isSecretLevelEnable } = this;
      // 需要判断是否只勾选了一项，并给出相应的提示
      if (selectedRows.length === 0) {
        //请选择要转发的协同
        Fiber.message.warning($.i18n('collaboration.grid.alert.transmitCol'));
        return false;
      } else if (selectedRows.length > 1 && isSecretLevelEnable) {
        Fiber.message.warning($.i18n('collabration.secret.transfer.num.limit'));
        return false;
      } else if (selectedRows.length > 20) {
        //只能选择20项协同进行转发
        Fiber.message.warning($.i18n('collaboration.grid.alert.transmitColOnly20'));
        return false;
      }
      console.log("$.ctp.trigger", "beforeTransmitCol", selectedRows);
      const sendDevelop = $.ctp.trigger('beforeTransmitCol', selectedRows);
      if (!sendDevelop) {
        return false;
      }
      return true;
    },
    rowApplicationValidate(application) {
      const notForwardColList = [19, 20, 21];
      if (notForwardColList.includes(application)) {
        //公文不允许转发协同
        Fiber.message.warning($.i18n('collaboration.grid.alert.DocumentNotForwardCol'));
        return false;
      } else if (application === 32) {
        //信息报送不允许转发协同
        Fiber.message.warning($.i18n('collaboration.grid.alert.InfoNotForwardCol'));
        return false;
      } else if (application === 81) {
        //模板审批不允许转发协同
        Fiber.message.warning($.i18n('collaboration.grid.alert.InfoNotTemplateApproveColl'));
        return false;
      } else if (application === 4) {
        Fiber.message.warning($.i18n('govdoc.grid.alert.DocumentNotForwardCol'));
        return false;
      }
      return true;
    },
    transmitColById(data) {
      const self = this;
      let checkPermissionData = '';
      let doForwardData = '';
      data.forEach((item) => {
        const { summaryId, affairId } = item;
        doForwardData += summaryId + '_' + affairId + ',';
        checkPermissionData += affairId + ',';
      });
      const result = window.callBackendMethod(
        'colManager',
        'checkForwardPermission',
        checkPermissionData
      );
      if (result && result instanceof Array && result.length > 0) {
        //以下协同不能转发，请重新选择
        toastForward.call(this, result);
        return;
      }
      const dialog = this._getCtpTop.$.dialog({
        id: 'showForwardDialog',
        height: '400',
        width: '550',
        url:
          window._ctxPath +
          '/collaboration/collaboration.do?method=showForward&data=' +
          doForwardData,
        title: $.i18n('common.toolbar.transmit.col.label'),
        isClear: false,
        transParams: {
          commentContent: ''
        },
        buttons: [
          {
            id: 'okButton',
            text: $.i18n('common.button.ok.label'),
            btnType: 1,
            handler: function handler() {
              dialog.getReturnValue();
            },
            OKFN: function OKFN() {
              self.resetTableData();
              dialog.close();
            }
          },
          {
            id: 'cancelButton',
            text: $.i18n('common.button.cancel.label'),
            handler: function handler() {
              dialog.close();
            }
          }
        ]
      });
    },
    // 邮件
    emailClickHandle() {
      const { emailShow, selectedRows, _getCtpTop } = this;
      if (emailShow) {
        //需要判断是否只勾选了一项，并给出相应的提示
        const validateResult = this.emailClickValidate();
        if (!validateResult) return;
        for (let i = 0; i < selectedRows.length; i++) {
          const row = selectedRows[i];
          let {
            applicationCategoryKey,
            app,
            summaryId,
            objectId,
            affairId,
            id,
            superNode,
          } = row;
          const application = applicationCategoryKey || app;
          const applicationValidateResult = this.rowApplicationValidate(application);
          if (!applicationValidateResult) return;
          summaryId = summaryId || objectId;
          affairId = affairId || id;
          const canTransSecretLevel = window.callBackendMethod("secretAjaxManager", "canTransSecretLevel", summaryId);
          if (!canTransSecretLevel) {
            Fiber.message.warning($.i18n('collaboration.grid.alert.noTransSecretData'));
            return;
          }
          const checkForwardPermission = callBackendMethod("colManager", "checkForwardPermission", affairId);
          if (checkForwardPermission && checkForwardPermission instanceof Array && checkForwardPermission.length > 0) {
            //以下协同不能转发，请重新选择
            toastForward.call(this, checkForwardPermission);
            return;
          }
          if (superNode === true) {
            Fiber.message.warning($.i18n("workflow.supernode.msg.not_transmit.js"));
            return;
          }
          let params = {};
          params.title = $.i18n('common.toolbar.transmit.mail.label');
          if (_getCtpTop && _getCtpTop.showMenu) {
            _getCtpTop.showMenu(_ctxPath + "/collaboration/collaboration.do?method=forwordMail&summaryId=" + summaryId + "&affairId=" + affairId, null, null, null, params);
          }
        }
      }
    },
    emailClickValidate() {
      const { selectedRows } = this;
      if (selectedRows.length === 0) {
        //请选择要转发的协同!
        Fiber.message.warning($.i18n('collaboration.grid.alert.transmitCol'));
        return false;
      } else if (selectedRows.length > 1) {
        //只能选择一项协同进行转发
        Fiber.message.warning($.i18n('collaboration.grid.alert.transmitColOnlyOne'));
        return false;
      }
      return true;
    },
    // 归档
    pigeonholeClickHandle() {
      const self = this;
      const { selectedRows } = this;
      if (!selectedRows.length) {
        Fiber.message.warning($.i18n('collaboration.pighole.alert.select'));
        return;
      }
      let secretBatchCheckParams = [];
      let ids = [];
      let check = false;
      let superNodeSubject = '';
      let canContinueExecute = true;
      const pageType = 'sent';
      selectedRows.forEach(row => {
        const { processId, affairId, summaryId, subject, superNode } = row;
        const param = new BatchParam(processId, affairId, summaryId, subject);
        secretBatchCheckParams.push(param);
        if (superNode) {
          check = true;
          superNodeSubject += "<br>" + "&lt;" + window.escapeStringToHTML(elem.subject) + "&gt;";
        }
      });
      if (!canContinueExecute) {
        return;
      }
      if (superNodeSubject.length > 1) {
        // 超级节点不允许转发
        $.alert({
          msg: $.i18n('workflow.supernode.msg.not_archive.js') + "<br>" + superNodeSubject,
          ok_fn: function ok_fn() {
            // 做兼容处理
            if (parent && parent.document.getElementById('mainIframe')) {
              parent.document.getElementById('mainIframe').contentWindow.location.reload(true);
            } else {
              window.location.reload(true);
            }
          }
        });
        unlockWorkflow();
        return;
      }
      if (check) {
        unlockWorkflow();
        return;
      }
      let secretCheckResult = callBackendMethod("secretAjaxManager", "batchCheckUserSecretLevel", secretBatchCheckParams);
      let secretCheck = new SecretCheck(secretCheckResult, 'pigeonhole');
      let affairIdArray = secretCheck.getSuccessAffairIds();

      if (affairIdArray.length === 0) {
        secretCheck.messageDialog(unlockWorkflow);
        return;
      }
      ids = affairIdArray; //let cm = new colManager();
      callBackendMethod("colManager", "getPigeonholeRight", ids, {
        success: function success(jsonObj) {
          if (jsonObj != "") {
            $.alert({
              msg: escapeStringToHTML(jsonObj),
              ok_fn: function ok_fn() {
                // 做兼容处理
                if (parent && parent.document.getElementById('mainIframe')) {
                  parent.document.getElementById('mainIframe').contentWindow.location.reload(true);
                } else {
                  window.location.reload(true);
                }
              }
            });
            unlockWorkflow();
          } else {
            doPigeonholeCheck(ids, pageType, '', '', secretCheck, self.resetTableData);
          }
        }
      });
    },
    async cancelWorkFlowClickHandle() {
      const self = this;
      window.matchRequestToken = generateRandomNumber();
      const { selectedRows } = this;
      if (!selectedRows.length) {
        //请选择需要撤销的协同！
        Fiber.message.warning($.i18n('collaboration.listSent.selectRevokeSyn'));
        return;
      }
      if (selectedRows.length > 1) {
        //只能选择一条记录!
        Fiber.message.warning($.i18n('collaboration.listSent.selectOneData'));
        return;
      }
      const selRow = selectedRows[0];
      const { affairId, summaryId, processId } = selRow;
      let idMap = {
        "summaryID": summaryId,
        "affairID": affairId
      };
      console.log("$.ctp.trigger", "beforeSentCancel", idMap);
      let sendDevelop = $.ctp.trigger('beforeSentCancel', idMap);
      if (!sendDevelop) return;
      // 校验开始
      let params = {};
      params["summaryId"] = summaryId;
      let checkResult = callBackendMethod("secretAjaxManager", "checkUserSecretLevel", summaryId);
      if (checkResult && checkResult.length > 0) {
        Fiber.message.warning(checkResult);
        return;
      }
      //校验是否流程结束、是否审核、是否核定，涉及到的子流程调用工作流接口校验
      let canDealCancel = callBackendMethod("colManager", "checkIsCanRepeal", params);
      if (canDealCancel.msg) {
        Fiber.message.warning(canDealCancel.msg);
        return;
      }
      if (!isAffairValid(affairId)) return;
      let validateResult = await onBeforeWorkflowOperationValidate(selRow.processId, "", "start", "", "", "collaboration", "repeal");
      if (validateResult && !validateResult.pass) {
        Fiber.message.warning(validateResult.msg);
        return;
      }
      let isForm = selRow.bodyType == '20';
      let appName = isForm ? "collaboration" : "form"; //调用工作流接口校验是否能够撤销流程
      let isSubmit = false; //撤销流程
      let dialog = $.dialog({
        url: _ctxPath + "/workflowmanage/workflowmanage.do?method=showRepealCommentDialog&affairId=" + affairId,
        width: 450,
        height: 240,
        title: $.i18n('common.toolbar.repeal.label'),
        //撤销流程
        targetWindow: getCtpTop(),
        buttons: [{
          text: $.i18n('common.button.ok.label'),
          //确定
          btnType: 1,
          handler: async function () {
            if (isSubmit) return;
            isSubmit = true;
            let returnValue = dialog.getReturnValue();
            if (!returnValue) {
              isSubmit = false;
              return;
            }
            let is4List = true;

            const beforeCancelParam = {
              event: 'BeforeCancel',
              bussinessId: summaryId,
              affairId,
              processTemplateId: processId,
              processId,
              activityId: selRow.activityId,
              formData: selRow.formRecordid,
              appName,
              formAppId: selRow.formAppId,
              formViewOperation: selRow.formViewOperation,
              processXml: '',
              attribute: returnValue[1],
              commentContent: returnValue[0],
              is4List
            };
            const result = await executeWorkflowBeforeEvent(beforeCancelParam);
            if (!result) {
              releaseWorkflowByAction(selRow.processId, window._currentUser.id.id, 12);
              return;
            }
            let ajaxSubmitFunc = () => {
              let tempMap = new Object();
              tempMap["repealComment"] = returnValue[0];
              tempMap["summaryId"] = summaryId;
              tempMap["affairId"] = affairId;
              tempMap["isWFTrace"] = returnValue[1];
              callBackendMethod("colManager", "transRepal", tempMap, {
                success: function success(msg) {
                  if (msg == null || msg == "") {
                    self.resetTableData();
                  } else {
                    Fiber.message.warning(msg);
                  } //撤销后关闭，子页面
                  try {
                    closeOpenMultyWindow(affairId);
                  } catch (e) { }
                  dialog.close();
                }
              });
            }; //V50_SP2_NC业务集成插件_001_表单开发高级
            beforeSubmit(affairId, "repeal", returnValue[0], dialog, ajaxSubmitFunc, function () {
              releaseWorkflowByAction(selRow.processId, window._currentUser.id.id, 12);
              dialog.close();
            });
          }
        }, {
          text: $.i18n('common.button.cancel.label'),
          //取消
          handler: function () {
            releaseWorkflowByAction(selRow.processId, window._currentUser.id, 12);
            dialog.close();
          }
        }],
        closeParam: {
          show: true,
          handler: function handler() {
            releaseWorkflowByAction(selRow.processId, window._currentUser.id.id, 12);
          }
        }
      });
    },
    editWorkFlowClickHandle() {
      const self = this;
      var affairId = "";
      var summaryId;
      const { selectedRows } = this;
      if (selectedRows.length === 1) {
        var selRow = selectedRows[0];
        affairId = selRow.affairId;
        summaryId = selRow.summaryId;
      }

      var bean = new Object();
      bean["affairId"] = affairId;

      _designWorkflow(selectedRows, function () {
        callBackendMethod("colManager", "transUpdateCurrentInfo", bean);

        try {
          self.resetTableData();
        } catch (e) { }
      });
    },
    resendClickHandle() {
      const { selectedRows, haveNewColl } = this;
      const rows = selectedRows;
      if (rows.length < 1) {
        //请选择要重复发起的协同
        Fiber.message.warning($.i18n('collaboration.grid.send.selectRepeatCol'));
        return;
      }
      if (rows.length > 1) {
        //只能选择一项协同进行重复发起
        Fiber.message.warning($.i18n('collaboration.grid.send.selectOneRepeatCol'));
        return;
      }
      let checkedObj = rows[0];
      const { summaryId, newflowType, bodyType, templeteId, parentformSummaryid, canEdit } = checkedObj;
      if (newflowType && newflowType == '1') {
        //该流程为自动触发的子流程，不能重发
        Fiber.message.warning($.i18n('collaboration.send.workFlow.notResend'));
        return;
      } //MainBodyType 里面20的时候表明是 表单格式正文
      if (bodyType && bodyType == '20') {
        //表单协同不能被重复发起
        Fiber.message.warning($.i18n('collaboration.send.fromSend.notResend'));
        return;
      } // 第三方正文协同暂不允许重复发起，bodyType为90时为第三方正文
      if (bodyType && bodyType == '90') {
        Fiber.message.warning($.i18n('collaboration.send.fromSend.thirdContent'));
        return;
      } //没有新建权限，自由协同不能重复发起
      if (!haveNewColl && (templeteId == null || templeteId == "")) {
        Fiber.message.warning($.i18n('collaboration.send.notNewPolicy.notResend.js'));
        return;
      }
      const bodyTypeList = ['41', '42', '43', '44', '45'];
      if (parentformSummaryid != null && !canEdit && !bodyTypeList.includes(bodyType)) {
        //转发表单不允许重复发起！
        Fiber.message.warning($.i18n('collaboration.send.fromSend.forwardFrom'));
        return;
      }
      var checkResult = callBackendMethod("secretAjaxManager", "checkUserSecretLevel", summaryId);
      if (checkResult && checkResult.length > 0) {
        Fiber.message.warning(checkResult);
        return;
      }

      console.log("$.ctp.trigger", "beforeResendCol", checkedObj);
      let sendDevelop = $.ctp.trigger('beforeResendCol', checkedObj);
      if (!sendDevelop) return;

      let url = "collaboration.do?method=newColl&summaryId=" + summaryId + "&from=resend";
      if (process.env.NODE_ENV !== 'production') {
        url = "/seeyon/collaboration/collaboration.do?method=newColl&summaryId=" + summaryId + "&from=resend";
      }
      window.openCtpWindow({
        'url': url
      });
    },
    deleteClickHandle() {
      const self = this;
      const pageType = 'sent';
      const tableId = 'listSent';
      const fromMethod = 'listSent';
      const { selectedRows } = this;
      if (!selectedRows.length) {
        // 请选择要删除的协同。
        Fiber.message.warning($.i18n('collaboration.grid.selectDelete'));
        return true;
      }
      console.log("$.ctp.trigger", "beforeDeleteColl");
      var sendDevelop = $.ctp.trigger('beforeDeleteColl');
      if (!sendDevelop) {
        return;
      }
      let deleteSubject = "";
      let secretBatchCheckParams = [];
      for (let i = 0; i < selectedRows.length; i++) {
        const row = selectedRows[i];
        let {
          applicationCategoryKey,
          app,
          summaryId,
          subject,
          objectId,
          affairId,
          id,
          templeteId,
          superNode,
          processId,
          canReMove
        } = row;
        const application = applicationCategoryKey || app;
        const param = new BatchParam(processId, affairId, summaryId, subject);
        secretBatchCheckParams.push(param);
        try {
          closeOpenMultyWindow(affairId, false);
        } catch (e) { }
        if (!canReMove) {
          if (selectedRows.length == 1) {
            //当前节点权限不可进行删除操作！
            Fiber.message.warning($.i18n('collaboration.alert.CantReMoveOne'));
            // 取消勾选
            this.cancelSelectedById(id);
            return true;
          } else {
            //根据当前节点权限以下流程不可删除！
            deleteSubject += "<br>&lt;" + escapeStringToHTML(obj.subject) + "&gt;";
            continue;
          }
        }
      }
      if (deleteSubject.length > 1) {
        Fiber.message.warning($.i18n('collaboration.alert.CantReMove') + deleteSubject);
        return true;
      } // end
      var confirm = $.confirm({
        // 该操作不能恢复，是否进行删除操作
        'msg': $.i18n('collaboration.confirmDelete'),
        ok_fn: ()=> {
          let affairIdArray = [];
          if ('draft' !== pageType) {
            var secretCheckResult = callBackendMethod("secretAjaxManager", "batchCheckUserSecretLevel", secretBatchCheckParams);
            var secretCheck = new SecretCheck(secretCheckResult, "delete");
            affairIdArray = secretCheck.getSuccessAffairIds();

            if (affairIdArray.length === 0) {
              secretCheck.messageDialog(unlockWorkflow);
              return;
            }
          } else {
            affairIdArray = [];

            for (var _i = 0; _i < secretBatchCheckParams.length; _i++) {
              affairIdArray.push(secretBatchCheckParams[_i].affairId);
            }
          }

          const affairIds = affairIdArray.join(","); // table提交
          var obj = new Object();
          obj.pageType = pageType;
          obj.affairIds = affairIds;
          obj.fromMethod = fromMethod; //collManager.checkCanDelete(obj,{});
          self.openProcessBar();
          callBackendMethod("colManager", "checkCanDelete", obj, {
            success: (flag)=> {
              if ("success" == flag) {
                // 循环删除，隔离后台的事务，否则多个流程事务一起提交工作流部分的数据可能会出错
                let ids = affairIds.split(",");
                self.openProcessBar();
                let callback = () => {
                  for (var i = 0; i < ids.length; i++) {
                    try {
                      closeOpenMultyWindow(ids[i], false);
                    } catch (e) { }
                  }

                  var successFn = function successFn() {
                    unlockWorkflow();
                    // 不知道干嘛的
                    // var totalNum = grid.p.total - 1;
                    // $('#summary').attr("src", "listDesc.do?method=listDesc&type=" + tableId + "&size=" + totalNum);
                    // 重新查询
                    self.resetTableData();
                  };

                  if (secretCheck && secretCheck.getCancelData().size() !== 0) {
                    secretCheck.messageDialog(successFn);
                    loadingInstance.close();
                    return;
                  } // 成功删除，并刷新列表


                  $.messageBox({
                    'title': $.i18n('common.system.hint.label'),
                    'type': 0,
                    'msg': $.i18n('common.delete.success.label'),
                    'imgType': 0,
                    ok_fn: function ok_fn() {
                      unlockWorkflow();
                      // 不知道干嘛的
                      //$('#summary').attr("src", "listDesc.do?method=listDesc&type=" + tableId + "&size=" + totalNum);
                      // 重新查询
                      self.resetTableData();
                      loadingInstance.close();
                    },
                    close_fn: function close_fn() {
                      unlockWorkflow();
                      // 不知道干嘛的
                      // $('#summary').attr("src", "listDesc.do?method=listDesc&type=" + tableId + "&size=" + totalNum);
                      // 重新查询
                      self.resetTableData();
                      loadingInstance.close();
                    }
                  });
                }
                this.deleteAffairAjax({ids,pageType,callback})
              } else {
                Fiber.message.warning(flag);
                unlockWorkflow();
                loadingInstance.close();
              }
            },
            error: function error(request, settings, e) {
              Fiber.message.warning(e);
              unlockWorkflow();
              loadingInstance.close();
            }
          });
        },
        "cancel_fn": function cancel_fn() {
          unlockWorkflow();
          loadingInstance.close();
        }
      });
    },

    deleteAffairAjax({ids, pageType, callback, count = 0}) {
      callBackendMethod("colManager", "deleteAffair", pageType, ids[count], {
        success: () => {
          if (++count < ids.length) {
            this.deleteAffairAjax({ids, pageType, callback, count})
          } else {
            callback.call(this)
          }
        }
      })
    },
    
    relationAuthorityClickHandle() {
      const self = this;
      const { selectedRows } = this;
      if (!selectedRows.length) {
        releaseApplicationButtons();
        Fiber.message.warning($.i18n('collaboration.listSent.selectAuthorized'));
        return;
      }
      var moduleIds = new Array();
      var affairIds = new Array();
      for (let i = 0; i < selectedRows.length; i++) {
        const row = selectedRows[i];
        const { bodyType, summaryId, affairId } = row;
        if (parseInt(bodyType) !== 20) {
          //只能对表单模板进行关联授权!
          Fiber.message.warning($.i18n('collaboration.listSent.onlyFromAuthorized'));
          releaseApplicationButtons();
          return;
        }
        moduleIds.push(summaryId);
        affairIds.push(affairId);
      }
      setRelationAuth(moduleIds, 1, function (flag) {
        var param = new Object();
        param.affairIds = affairIds;
        param.flag = flag;
        callBackendMethod("colManager", "updateAffairIdentifierForRelationAuth", param, {
          success: function success() {
            releaseApplicationButtons();
            self.resetTableData();
          }
        });
      }, releaseApplicationButtons);
    },
    // 配置
    currentDataClickHandle() {
      this.disabledToolbar();
      this.dataType = '0';
      this.resetTableData();
    },
    dumpDataClickHandle() {
      this.disabledToolbar();
      this.dataType = '1';
      this.resetTableData();
    },
    disabledToolbar() {
      this.allToolBtns.forEach(item => {
        if (!['currentData', 'dumpData'].includes(item.id)) {
          item.disabled = true;
        }
      });
    },
    // 配置
    toClickHandle() {
      this.handoverType = "toMe";
    },
    fromClickHandle() {
      this.handoverType = "fromMe";
    },
    deduplicationClickHandle(value) {
      this.deduplication = value;
    },
    aiProcessingClickHandle(value) {
      this.aiProcessing = value;
    },
    smartCodeScanClickHandle() {
      this.showSmartCode && this.showSmartCode();
    },
    // 智码扫码成功后，智码预处理时，获取解码参数
    getSmartCodeDecodeParam(data) {
      const obj = this.searchConditionsValue;
      obj.openFrom = 'listSent';
      return obj;
    },
    // 智码扫码成功后回调
    smartCodeCallBack(data) {
      collaboration.smartCodeCallBack(data);
    },
    openProcessBar(){
      if (loadingInstance.empty){
        //动态引入防止新建页面错误逻辑发送后出现转圈
        import(/* webpackChunkName: "chunk-loading" */ '@/utils/loading.js')
            .then(md=>loadingInstance=md.loadingInstance)
        return;
      }
      loadingInstance.show();
    }
  }
};
